package logger

import (
	"fmt"
	"log/slog"
	"os"
	"path/filepath"
	"time"
)

var (
	SLogger *slog.Logger
	LogFile *os.File
)

func InitSlog(appName string) error {
	var (
		err error
	)

	if SLogger != nil && LogFile != nil {
		if errClose := LogFile.Close(); errClose != nil {
			fmt.Println("关闭日志文件错误:", errClose)
		}
	}

	today := time.Now().Format(time.DateOnly)
	//文件夹需要自己手动创建 如 log appName
	logFilePath := filepath.Join("./log", appName, today+".log")

	LogFile, err = os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}

	SLogger = slog.New(slog.NewJSONHandler(LogFile, &slog.HandlerOptions{
		AddSource:   true,
		Level:       slog.LevelDebug,
		ReplaceAttr: nil,
	}))

	return nil

}
